
local ngx = ngx
local json = require "dkjson"
local ngx_config_prefix = ngx.config.prefix
local prefix
if type(ngx_config_prefix) == "string" then
    -- 测试框架使用
    prefix = ngx_config_prefix
else
    prefix = ngx_config_prefix()
end
local log = require("core.log").new("config: ")
local io = io

local _M = {}

local app_config = {}
local plugin_config = {}


local function get(key)
    if not app_config then
        log.error("config not init")
        return nil
    end
    return app_config[key]
end



_M.get = get

local function get_plugin(key)
    if not plugin_config then
        log.error("plugin config not init")
        return nil
    end
    return plugin_config[key]
end
_M.get_plugin = get_plugin
-- 获取etcd配置
local function get_etcd_config()
    return get("etcd")
end

_M.get_etcd_config = get_etcd_config

-- 是否是测试环境
function _M.is_test()
    return not app_config.env == "prod"
end

local function readfile(filename)
    --log.error(type(ngx_config.prefix))
    local config_file = prefix .. filename
    log.notice("load config file: ", config_file)
    local jsonFile,err = io.open(config_file, "r")
    if not jsonFile then
        log.error("failed to open file: " .. config_file .. ", error info:" .. err)
    end

    local jsonStr = jsonFile:read("*a")
    log.info("decode json data: ", jsonStr)
    jsonFile:close()
    return json.decode(jsonStr)
end


function _M.init()

    app_config = readfile("service/etc/app.json")

    for _,plugin in ipairs(app_config["plugins"]) do
        --log.error(plugin)
        if app_config[plugin] ~= nil then
            local  config_path  = app_config[plugin]["conf_path"]
            --log.error(plugin,app_config[plugin]["conf_path"])
            if config_path ~= nil then
                --log.error(plugin,readfile("service/etc/" .. config_path))

                plugin_config[plugin] = readfile("service/etc/" .. config_path)
            end
        end
    end

    --log.error(json.decode(plugin_config["filter"]))
end

return _M
